<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, TeamOutlined, LoadingOutlined, EyeOutlined } from '@ant-design/icons-vue'
import { useWallet } from '../../../composables/useWallet'

// 使用钱包
const {
  isConnected,
  isReady,
  currentAccount,
  getContract,
} = useWallet()

// 组件挂载时自动加载家族列表
onMounted(() => {
  console.log('📱 FamilyRegistry 组件已挂载')
  if (isReady.value) {
    loadFamilyList()
  }
})

// 监听钱包连接状态变化，自动加载家族列表
watch(isReady, (ready) => {
  if (ready) {
    console.log('🔗 钱包已准备，自动加载家族列表')
    loadFamilyList()
  }
})

// 表单数据
const registerForm = ref({
  familyName: '',
  ancestralHome: '',
  foundedYear: new Date().getFullYear(),
})

// 家族列表
const familyList = ref<any[]>([])

// 加载状态
const isRegistering = ref(false)
const isLoadingList = ref(false)

// 模态框
const registerModalVisible = ref(false)

/**
 * 注册家族
 */
async function registerFamily() {
  if (!isReady.value) {
    message.error('请先连接钱包并切换到正确的网络')
    return
  }

  if (!registerForm.value.familyName || !registerForm.value.ancestralHome) {
    message.error('请填写完整的家族信息')
    return
  }

  isRegistering.value = true

  try {
    console.log('🏛️ 开始注册家族...')
    
    // 获取合约实例
    const registryContract = getContract('registry')
    
    // 调用合约方法注册家族
    // 实际合约中的方法名是 createFamily(string name, string ancestralHome, uint256 foundedYear)
    const tx = await registryContract.methods
      .createFamily(
        registerForm.value.familyName,
        registerForm.value.ancestralHome,
        registerForm.value.foundedYear
      )
      .send({
        from: currentAccount.value,
        gas: 500000,  // 增加 Gas 限制
      })
    
    console.log('✅ 家族注册成功！交易哈希:', tx.transactionHash)
    
    message.success({
      content: `家族 "${registerForm.value.familyName}" 注册成功！`,
      duration: 5,
    })
    
    // 重置表单
    registerForm.value = {
      familyName: '',
      ancestralHome: '',
      foundedYear: new Date().getFullYear(),
    }
    
    // 关闭模态框
    registerModalVisible.value = false
    
    // 刷新家族列表
    await loadFamilyList()
    
  } catch (error: any) {
    console.error('❌ 家族注册失败:', error)
    
    if (error.code === 4001) {
      message.error('用户取消了交易')
    } else if (error.message?.includes('already registered')) {
      message.error('该家族名称已被注册')
    } else {
      message.error(`注册失败: ${error.message || '未知错误'}`)
    }
  } finally {
    isRegistering.value = false
  }
}

/**
 * 加载家族列表
 */
async function loadFamilyList() {
  if (!isReady.value) return

  isLoadingList.value = true

  try {
    console.log('📋 加载家族列表...')
    
    // 调用后端 API 获取家族列表
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const response = await fetch(`${apiBaseUrl}/blockchain/family/list`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('📡 后端返回:', result)
    
    if (result.code === 200 && result.data) {
      // 转换后端数据格式到前端格式
      const families = result.data.map((family: any) => ({
        id: String(family.id),
        name: family.name || '',
        description: family.ancestralHome || '', // 祖籍地作为描述
        founder: family.patriarch || '',
        memberCount: Number(family.memberCount || 0),
        createdAt: Number(family.createdAt || 0),
        foundedYear: Number(family.foundedYear || 0),
      }))
      
      familyList.value = families
      console.log('✅ 家族列表加载完成:', families.length)
      
      if (families.length === 0) {
        message.info('暂无家族数据，请先注册新家族')
      }
    } else {
      throw new Error(result.message || '获取家族列表失败')
    }
    
  } catch (error: any) {
    console.error('❌ 加载家族列表失败:', error)
    message.error(`加载家族列表失败: ${error.message || '请稍后重试'}`)
  } finally {
    isLoadingList.value = false
  }
}

// 家族详情
const selectedFamily = ref<any>(null)
const familyDetailModalVisible = ref(false)
const familyDetailLoading = ref(false)

/**
 * 查看家族详情
 */
async function viewFamily(family: any) {
  familyDetailLoading.value = true
  familyDetailModalVisible.value = true
  
  try {
    console.log('🔍 加载家族详情:', family.id)
    
    // 调用后端 API 获取家族详细信息
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
    const response = await fetch(`${apiBaseUrl}/blockchain/family/${family.id}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('📡 家族详情:', result)
    
    if (result.code === 200 && result.data) {
      selectedFamily.value = {
        ...family,
        ...result.data,
        // 确保所有字段都有值
        name: result.data.name || family.name,
        ancestralHome: result.data.ancestralHome || family.description,
        patriarch: result.data.patriarch || family.founder,
        memberCount: result.data.memberCount || family.memberCount,
        createdAt: result.data.createdAt || family.createdAt,
        foundedYear: result.data.foundedYear || family.foundedYear,
      }
      console.log('✅ 家族详情加载完成')
    } else {
      throw new Error(result.message || '获取家族详情失败')
    }
    
  } catch (error: any) {
    console.error('❌ 加载家族详情失败:', error)
    message.error(`加载家族详情失败: ${error.message || '请稍后重试'}`)
    // 出错时使用列表中的基本信息
    selectedFamily.value = family
  } finally {
    familyDetailLoading.value = false
  }
}

/**
 * 格式化时间戳
 */
function formatTimestamp(timestamp: number) {
  if (!timestamp) return '-'
  return new Date(timestamp * 1000).toLocaleString('zh-CN')
}

/**
 * 格式化地址
 */
function formatAddress(address: string) {
  if (!address) return '-'
  return `${address.slice(0, 6)}...${address.slice(-4)}`
}
</script>

<template>
  <div class="family-registry">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h2><TeamOutlined /> 家族注册中心</h2>
        <p>在区块链上注册您的家族，永久记录家族信息</p>
      </div>
      <a-button
        v-if="isConnected"
        type="primary"
        size="large"
        @click="registerModalVisible = true"
      >
        <PlusOutlined /> 注册新家族
      </a-button>
    </div>

    <!-- 未连接钱包提示 -->
    <a-alert
      v-if="!isConnected"
      type="warning"
      message="请先连接钱包"
      description="您需要连接 MetaMask 钱包才能注册家族和查看链上数据"
      show-icon
      style="margin-bottom: 24px"
    />

    <!-- 网络错误提示 -->
    <a-alert
      v-else-if="!isReady"
      type="error"
      message="网络错误"
      description="请切换到正确的网络 (FamilyChain)"
      show-icon
      style="margin-bottom: 24px"
    />

    <!-- 家族列表 -->
    <a-card v-else title="已注册家族" style="margin-top: 24px">
      <template #extra>
        <a-button @click="loadFamilyList" :loading="isLoadingList">
          刷新列表
        </a-button>
      </template>

      <a-spin :spinning="isLoadingList" tip="加载中...">
        <a-empty v-if="familyList.length === 0" description="还没有注册的家族">
          <a-button type="primary" @click="registerModalVisible = true">
            <PlusOutlined /> 立即注册
          </a-button>
        </a-empty>

        <a-list
          v-else
          :data-source="familyList"
          :grid="{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-card hoverable @click="viewFamily(item)">
                <template #title>
                  <div style="display: flex; align-items: center; gap: 8px">
                    <TeamOutlined style="color: #1890ff" />
                    <span>{{ item.name }}</span>
                  </div>
                </template>
                
                <a-descriptions :column="1" size="small">
                  <a-descriptions-item label="家族 ID">
                    {{ formatAddress(item.id) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="创始人">
                    {{ formatAddress(item.founder) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="成员数">
                    {{ item.memberCount }}
                  </a-descriptions-item>
                  <a-descriptions-item label="创建时间">
                    {{ formatTimestamp(item.createdAt) }}
                  </a-descriptions-item>
                </a-descriptions>
                
                <p style="margin-top: 12px; color: #666">
                  {{ item.description }}
                </p>
              </a-card>
            </a-list-item>
          </template>
        </a-list>
      </a-spin>
    </a-card>

    <!-- 注册家族模态框 -->
    <a-modal
      v-model:open="registerModalVisible"
      title="注册新家族"
      :confirm-loading="isRegistering"
      @ok="registerFamily"
      @cancel="registerModalVisible = false"
      width="600px"
    >
      <a-form :model="registerForm" layout="vertical">
        <a-form-item
          label="家族名称"
          required
          help="家族名称将永久记录在区块链上，不可修改"
        >
          <a-input
            v-model:value="registerForm.familyName"
            placeholder="请输入家族名称，如：朱氏皇族"
            size="large"
            :maxlength="50"
            show-count
          />
        </a-form-item>

        <a-form-item
          label="祖籍地"
          required
          help="家族的祖籍所在地"
        >
          <a-input
            v-model:value="registerForm.ancestralHome"
            placeholder="请输入祖籍地，如：江苏南京"
            size="large"
            :maxlength="100"
            show-count
          />
        </a-form-item>

        <a-form-item
          label="建立年份"
          help="家族建立的年份"
        >
          <a-input-number
            v-model:value="registerForm.foundedYear"
            placeholder="请输入年份"
            size="large"
            :min="1000"
            :max="9999"
            style="width: 100%"
          />
        </a-form-item>

        <a-alert
          type="info"
          message="Gas 费用提示"
          :description="`注册家族需要支付少量 Gas 费用。当前账户: ${formatAddress(currentAccount || '')}`"
          show-icon
        />
      </a-form>
    </a-modal>

    <!-- 家族详情模态框 -->
    <a-modal
      v-model:open="familyDetailModalVisible"
      :title="`家族详情 - ${selectedFamily?.name || ''}`"
      :footer="null"
      width="800px"
    >
      <a-spin :spinning="familyDetailLoading" tip="加载详情中...">
        <div v-if="selectedFamily" class="family-detail">
          <a-descriptions bordered :column="2">
            <a-descriptions-item label="家族 ID" :span="2">
              {{ selectedFamily.id }}
            </a-descriptions-item>
            
            <a-descriptions-item label="家族名称">
              {{ selectedFamily.name }}
            </a-descriptions-item>
            
            <a-descriptions-item label="创建年份">
              {{ selectedFamily.foundedYear }} 年
            </a-descriptions-item>
            
            <a-descriptions-item label="祖籍地" :span="2">
              {{ selectedFamily.ancestralHome || selectedFamily.description }}
            </a-descriptions-item>
            
            <a-descriptions-item label="族长">
              <a-typography-text copyable>
                {{ selectedFamily.patriarch || selectedFamily.founder }}
              </a-typography-text>
            </a-descriptions-item>
            
            <a-descriptions-item label="成员数量">
              <a-tag color="blue">{{ selectedFamily.memberCount }} 人</a-tag>
            </a-descriptions-item>
            
            <a-descriptions-item label="创建时间" :span="2">
              {{ formatTimestamp(selectedFamily.createdAt) }}
            </a-descriptions-item>
          </a-descriptions>
          
          <div style="margin-top: 24px; text-align: right">
            <a-space>
              <a-button @click="familyDetailModalVisible = false">
                关闭
              </a-button>
              <a-button type="primary" @click="() => { familyDetailModalVisible = false; $router.push(`/zhu-family/blockchain/members?familyId=${selectedFamily.id}`) }">
                <TeamOutlined /> 管理成员
              </a-button>
            </a-space>
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.family-registry {
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24px;
    margin-bottom: 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    color: white;
    
    .header-content {
      h2 {
        margin: 0 0 8px;
        font-size: 28px;
        color: white;
      }
      
      p {
        margin: 0;
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }
  
  :deep(.ant-card) {
    transition: all 0.3s;
    
    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      transform: translateY(-2px);
    }
  }
  
  :deep(.ant-descriptions-item-label) {
    font-weight: 500;
  }
}
</style>

